/*
 * i2c-decoder.c
 *
 *  Created on: 2024年4月11日
 *      Author: NI
 */
#include <errno.h>
#include "i2c-platfrom.h"
#include <stdio.h>
#include <string.h>


static int fd;
static uint8_t decoder_addr;

int i2c_decoder_init(char * path, uint8_t addr){
	decoder_addr = addr;
	fd = capture_i2c_open(path);
	if(fd < 0){
		return EIO;
	}
	return EOK;
}

int i2c_decoder_deinit(){
	capture_i2c_close(fd);
	return EOK;
}

int i2c_decoder_set_speed(uint32_t speed){
	return capture_i2c_set_speed(fd, speed);
}

int i2c_decoder_rd(uint8_t reg, uint8_t * data){
	return capture_i2c_rd(fd, decoder_addr, reg, data);
}

int i2c_decoder_wr(uint8_t reg, uint8_t value){
	return capture_i2c_wr(fd, decoder_addr, reg, value);
}

int i2c_decoder_dump(){
	#define REG_DUMP_CNT 256

	int i = 0, j = 0;
	uint8_t data[REG_DUMP_CNT];
	char log[2048] = {0};
	capture_i2c_dump(fd, decoder_addr, 0x00, data, REG_DUMP_CNT);
	sprintf(&log[strlen(log)], "    0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f\n");
	for (i = 0; i < REG_DUMP_CNT; i++) {
		if ((i & 0xf) == 0) {
			sprintf(&log[strlen(log)], "%02x:", j);
		}
		sprintf(&log[strlen(log)], " %02x", data[i]);
		if ((i & 0xf) == 0x0f) {
			sprintf(&log[strlen(log)], "\n");
		}
		j++;
	}
	sprintf(&log[strlen(log)], "\n");

	printf("%s\n", log);

	return EOK;
}
